package com.lvy.hczn.front.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvy.hczn.front.common.constant.Constants;
import com.lvy.hczn.front.common.core.domain.BaseModel;
import com.lvy.hczn.front.common.core.domain.entity.SysDictData;
import com.lvy.hczn.front.common.core.text.Convert;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.common.utils.DictUtils;
import com.lvy.hczn.front.system.domain.business.GoodsBoxSpec;
import com.lvy.hczn.front.system.domain.transmit.SupplierBoxBatchNumber;
import com.lvy.hczn.front.system.domain.transmit.dto.SupplierBoxBatchNumberExport;
import com.lvy.hczn.front.system.mapper.GoodsBoxSpecMapper;
import com.lvy.hczn.front.system.mapper.SupplierBoxBatchNumberMapper;
import com.lvy.hczn.front.system.service.SupplierBoxBatchNumberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SupplierBoxBatchNumberServiceImpl extends ServiceImpl<SupplierBoxBatchNumberMapper, SupplierBoxBatchNumber> implements SupplierBoxBatchNumberService {

    @Autowired
    private SupplierBoxBatchNumberMapper supplierBoxBatchNumberMapper;

    @Autowired
    private GoodsBoxSpecMapper goodsBoxSpecMapper;

    /**
     * 查询供应商批次编号管理，供应商生成货箱时的批次和编号，下一批次和编号在记录上累加后更新列表
     *
     * @param supplierBoxBatchNumber 供应商批次编号管理，供应商生成货箱时的批次和编号，下一批次和编号在记录上累加后更新
     * @return 供应商批次编号管理，供应商生成货箱时的批次和编号，下一批次和编号在记录上累加后更新
     */
    @Override
    public List<SupplierBoxBatchNumber> selectSupplierBoxBatchNumberList(SupplierBoxBatchNumber supplierBoxBatchNumber) {
        return supplierBoxBatchNumberMapper.selectSupplierBoxBatchNumberList(supplierBoxBatchNumber);
    }

    /**
     * 批量删除供应商批次编号管理，供应商生成货箱时的批次和编号，下一批次和编号在记录上累加后更新
     *
     * @param ids 需要删除的供应商批次编号管理，供应商生成货箱时的批次和编号，下一批次和编号在记录上累加后更新主键
     * @return 结果
     */
    @Override
    public int deleteSupplierBoxBatchNumberByIds(String ids) {
        if (StrUtil.isEmpty(ids)) {
            throw new UtilException("ID为空");
        }
        String[] arrId = Convert.toStrArray(ids);
        for (String id : arrId) {
            super.removeById(id);
        }
        return arrId.length;
    }

    /**
     * 生成货箱编号
     * 货箱编号生成方式：DM0100001000->DM：供应商名称；0/1：货箱类型，（0，大货箱，1，小货箱）；10000：批次（累加）；1000：货箱编号（累加）
     * 即：供应商大小货箱总共可以生成生成99999次货箱编码，每次生成货箱编码最多可以生成9999个
     *
     * @param supplierBoxBatchNumber
     * @return java.util.List<com.lvy.hczn.front.system.domain.transmit.dto.SupplierBoxBatchNumberExport>
     * @author yw
     * @date 2023-05-17 16:31:27
     */
    @Override
    public synchronized List<SupplierBoxBatchNumberExport> generateBoxNumber(SupplierBoxBatchNumber supplierBoxBatchNumber) {
        List<SupplierBoxBatchNumberExport> list = new ArrayList<>();
        if (StrUtil.isEmpty(supplierBoxBatchNumber.getBoxPrefix())) {
            throw new UtilException("前缀为空");
        }
        if (StrUtil.isEmpty(supplierBoxBatchNumber.getGoodsBoxSpecId())) {
            throw new UtilException("请选择货箱类型");
        }
        //货箱编号生成方式：DM0100001000->DM：供应商名称；0/1：货箱类型，（0，大货箱，1，小货箱）；10000：批次（累加）；1000：货箱编号（累加）
        //即：供应商大小货箱总共可以生成生成99999次货箱编码，每次生成货箱编码最多可以生成9999个
        if (supplierBoxBatchNumber != null && supplierBoxBatchNumber.getNumber() > 0) {
            GoodsBoxSpec goodsBoxSpec = goodsBoxSpecMapper.selectById(supplierBoxBatchNumber.getGoodsBoxSpecId());
            if (goodsBoxSpec == null) {
                throw new UtilException("货箱类型数据不存在");
            }

            /**平台货箱规格无编码，用货箱数占库位数digitCapacity来判断是大货箱还是小货箱，1则是大货箱，0.5则是小货箱**/
            List<SysDictData> sysDictDataList = DictUtils.getDictCache(Constants.BOX_SIZE_INFO);
            if (sysDictDataList == null || sysDictDataList.size() == 0) {
                throw new UtilException("货箱类型字典为空");
            }
            for (SysDictData sysDictData : sysDictDataList) {
                if (sysDictData.getDictLabel().equals(Constants.BOX_SIZE_DIGIT_CAPACITY_SMALL) && sysDictData.getDictValue().equals(String.valueOf(goodsBoxSpec.getDigitCapacity()))) {
                    supplierBoxBatchNumber.setType(Constants.BOX_SIZE_SMALL);
                } else if (sysDictData.getDictLabel().equals(Constants.BOX_SIZE_DIGIT_CAPACITY_BIG) && sysDictData.getDictValue().equals(String.valueOf(goodsBoxSpec.getDigitCapacity()))) {
                    supplierBoxBatchNumber.setType(Constants.BOX_SIZE_BIG);
                }
            }
            if (supplierBoxBatchNumber.getType() == null) {
                throw new UtilException("数据字典设置货箱类型异常");
            }

            String prefix = supplierBoxBatchNumber.getBoxPrefix() + supplierBoxBatchNumber.getType();
            SupplierBoxBatchNumber model = super.getOne(Wrappers.<SupplierBoxBatchNumber>lambdaQuery().eq(SupplierBoxBatchNumber::getBoxPrefix, supplierBoxBatchNumber.getBoxPrefix()).orderByDesc(BaseModel::getUpdateTime));
            //第一次生成货箱编号的时候，默认为0处理
            int tempCurNumber = 0;
            if (model != null) {
                /**批次生成**/
                // 字符串数字解析为整数
                int batchNo = Integer.parseInt(model.getCurBatch());
                // 最新设备编号自增1
                int newBatchNo = ++batchNo;
                String resultBatchNo = String.format("%05d", newBatchNo);
                model.setCurBatch(resultBatchNo);
                prefix = prefix + resultBatchNo;
            } else {
                model = new SupplierBoxBatchNumber();
                model.setBoxPrefix(supplierBoxBatchNumber.getBoxPrefix());
                //第一次
                /**批次生成**/
                // 字符串数字解析为整数
                int batchNo = 0;
                // 最新设备编号自增1
                int newBatchNo = ++batchNo;
                String resultBatchNo = String.format("%05d", newBatchNo);
                model.setCurBatch(resultBatchNo);
                prefix = prefix + resultBatchNo;
            }

            for (int i = 0; i < supplierBoxBatchNumber.getNumber(); i++) {
                SupplierBoxBatchNumberExport export = new SupplierBoxBatchNumberExport();
                if (model != null && !StrUtil.isEmpty(model.getCurNumber())) {
                    /**编号生成**/
                    int codeNumber = Integer.parseInt(model.getCurNumber());
                    int newNumber = ++codeNumber;
                    String resultNumber = String.format("%04d", newNumber);
                    model.setCurNumber(resultNumber);
                    export.setBoxNumber(prefix + resultNumber);
                } else {
                    /**第一次编号生成**/
                    int codeNumber = tempCurNumber;
                    int newNumber = ++codeNumber;
                    String resultNumber = String.format("%04d", newNumber);
                    tempCurNumber = newNumber;
                    model.setCurNumber(resultNumber);

                    export.setBoxNumber(prefix + resultNumber);
                }
                list.add(export);
            }
            model.setCurNumber("0");
            model.setSupplierName(supplierBoxBatchNumber.getSupplierName());
            model.setSupplierCode(supplierBoxBatchNumber.getSupplierCode());
            this.saveOrUpdate(model);
        }
        return list;
    }
}
